<template>
  <div class="application-container">
    <!-- 搜索区域 -->
    <a-card class="search-card" :bordered="false">
      <a-form ref="searchFormRef" :model="searchForm" class="search-form">
        <div class="search-row">
          <a-form-item
            label="系统编码"
            name="code"
            class="search-item"
          >
            <a-input
              v-model:value="searchForm.code"
              placeholder="请输入系统编码"
              allow-clear
            />
          </a-form-item>

          <a-form-item label="系统名称" name="name" class="search-item">
            <a-input
              v-model:value="searchForm.name"
              placeholder="请输入系统名称"
              allow-clear
            />
          </a-form-item>

          <a-form-item label="系统状态" name="status" class="search-item">
            <a-select
              v-model:value="searchForm.status"
              placeholder="请选择系统状态"
              allow-clear
            >
              <a-select-option value="NEW">新建</a-select-option>
              <a-select-option value="ENABLE">启用</a-select-option>
              <a-select-option value="DISABLE">禁用</a-select-option>
            </a-select>
          </a-form-item>
        </div>
        <div class="search-row">
          <a-form-item label="负责人" name="ownerId" class="search-item">
            <a-select
              v-model:value="searchForm.ownerId"
              placeholder="请选择负责人"
              allow-clear
              show-search
              :filter-option="filterUserOption"
            >
              <a-select-option
                v-for="user in userList"
                :key="user.id"
                :value="user.id"
              >
                {{ user.name }}
              </a-select-option>
            </a-select>
          </a-form-item>

          <a-form-item label="" class="search-item search-buttons">
            <a-space>
              <a-button type="primary" @click="handleSearch">
                <template #icon><search-outlined /></template>
                查询
              </a-button>
              <a-button @click="handleReset">
                <template #icon><reload-outlined /></template>
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </div>
      </a-form>
    </a-card>

    <!-- 数据表格区域 -->
    <a-card class="table-card" :bordered="false">
      <template #title>
        <div class="card-header">
          <a-button v-permission="'system:application:create'" type="primary" @click="handleAdd">
            <template #icon><plus-outlined /></template>
            添加系统
          </a-button>
        </div>
      </template>

      <a-table
        :dataSource="applicationList"
        :columns="columns"
        :loading="loading"
        :pagination="pagination"
        rowKey="id"
        bordered
        size="small"
        @change="handleTableChange"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'status'">
            <a-tag :color="getStatusColor(record.status)">
              {{ getStatusText(record.status) }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'ownerName'">
            {{ getUserName(record.ownerId) }}
          </template>

          <template v-else-if="column.key === 'action'">
            <div class="action-btns">
              <a-button
                v-if="record.status === 'NEW'"
                v-permission="'system:application:update'"
                type="link"
                @click="handleEdit(record)"
              >
                编辑
              </a-button>

              <a-button
                v-if="record.status === 'DISABLE' || record.status === 'NEW'"
                v-permission="'system:application:enable'"
                type="link"
                @click="handleEnable(record)"
              >
                启用
              </a-button>

              <a-button
                v-if="record.status === 'ENABLE'"
                v-permission="'system:application:disable'"
                type="link"
                danger
                @click="handleDisable(record)"
              >
                禁用
              </a-button>

              <a-button
                v-if="record.status === 'NEW'"
                v-permission="'system:application:delete'"
                type="link"
                danger
                @click="handleDelete(record)"
              >
                删除
              </a-button>
            </div>
          </template>
        </template>
      </a-table>
    </a-card>

    <!-- 添加/编辑弹窗 -->
    <ApplicationForm
      v-model:visible="formVisible"
      :application-data="currentApplication"
      :is-edit="isEdit"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import {
  PlusOutlined,
  SearchOutlined,
  ReloadOutlined,
} from "@ant-design/icons-vue";
import { message, Modal } from "ant-design-vue";
import ApplicationForm from "./components/ApplicationForm.vue";
import {
  getApplicationList,
  deleteApplication,
  enableApplication,
  disableApplication,
} from "@/api/application";
import { getEmployeeList } from "@/api/employee";

// 搜索表单
const searchFormRef = ref();
const searchForm = reactive({
  code: undefined,
  name: undefined,
  status: undefined,
  ownerId: undefined,
});

// 用户列表
const userList = ref([]);

// 表格数据
const applicationList = ref([]);
const loading = ref(false);

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/共 ${total} 条`,
});

// 表单弹窗
const formVisible = ref(false);
const currentApplication = ref(null);
const isEdit = ref(false);

// 表格列定义
const columns = [
  {
    title: "ID",
    dataIndex: "id",
    key: "id",
    width: 80,
  },
  {
    title: "应用编码",
    dataIndex: "code",
    key: "code",
    width: 120,
  },
  {
    title: "应用名称",
    dataIndex: "name",
    key: "name",
    width: 150,
  },
  {
    title: "应用状态",
    dataIndex: "status",
    key: "status",
    width: 100,
  },
  {
    title: "排序值",
    dataIndex: "sort",
    key: "sort",
    width: 80,
  },
  {
    title: "负责人",
    dataIndex: "ownerName",
    key: "ownerName",
    width: 120,
  },
  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    ellipsis: true,
  },
  {
    title: "创建时间",
    dataIndex: "createTime",
    key: "createTime",
    width: 180,
  },
  {
    title: "操作",
    key: "action",
    width: 200,
    fixed: "right",
  },
];

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    NEW: "新建",
    ENABLE: "启用",
    DISABLE: "禁用",
  };
  return statusMap[status] || status;
};

// 获取状态颜色
const getStatusColor = (status) => {
  const colorMap = {
    NEW: "default",
    ENABLE: "success",
    DISABLE: "error",
  };
  return colorMap[status] || "default";
};

// 获取用户名称
const getUserName = (userId) => {
  const user = userList.value.find((u) => u.id === userId);
  return user ? user.name : "-";
};

// 用户搜索过滤
const filterUserOption = (input, option) => {
  const user = userList.value.find((u) => u.id === option.value);
  if (!user) return false;
  return user.name.toLowerCase().includes(input.toLowerCase());
};

// 获取应用列表
const fetchApplicationList = async () => {
  try {
    loading.value = true;
    const params = {
      ...searchForm,
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    };

    const response = await getApplicationList(params);
    applicationList.value = response.data.items || [];
    pagination.total = response.data.total || 0;
  } catch (error) {
    message.error("获取应用列表失败");
  } finally {
    loading.value = false;
  }
};

// 获取用户列表
const fetchUserList = async () => {
  try {
    const response = await getEmployeeList();
    // 根据实际API响应结构调整数据解析
    if (response.data) {
      userList.value = response.data.items || response.data || [];
    }
  } catch (error) {
    message.error("获取用户列表失败");
  }
};

// 搜索
const handleSearch = () => {
  pagination.current = 1;
  fetchApplicationList();
};

// 重置
const handleReset = () => {
  searchFormRef.value.resetFields();
  pagination.current = 1;
  fetchApplicationList();
};

// 表格变化
const handleTableChange = (pag) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  fetchApplicationList();
};

// 添加应用
const handleAdd = () => {
  currentApplication.value = null;
  isEdit.value = false;
  formVisible.value = true;
};

// 编辑应用
const handleEdit = (record) => {
  currentApplication.value = { ...record };
  isEdit.value = true;
  formVisible.value = true;
};

// 删除系统
const handleDelete = (record) => {
  Modal.confirm({
    title: "确认删除",
    content: `确定要删除系统"${record.name}"吗？`,
    okText: "确定",
    cancelText: "取消",
    onOk: async () => {
      try {
        await deleteApplication(record.id);
        message.success("删除成功");
        fetchApplicationList();
      } catch (error) {
        message.error("删除失败");
      }
    },
  });
};

// 启用应用
const handleEnable = (record) => {
  Modal.confirm({
    title: "确认启用",
    content: `确定要启用应用"${record.name}"吗？`,
    okText: "确定",
    cancelText: "取消",
    onOk: async () => {
      try {
        await enableApplication(record.id);
        message.success("启用成功");
        fetchApplicationList();
      } catch (error) {
        message.error("启用失败");
      }
    },
  });
};

// 禁用系统
const handleDisable = (record) => {
  Modal.confirm({
    title: "确认禁用",
    content: `确定要禁用系统"${record.name}"吗？`,
    okText: "确定",
    cancelText: "取消",
    onOk: async () => {
      try {
        await disableApplication(record.id);
        message.success("禁用成功");
        fetchApplicationList();
      } catch (error) {
        message.error("禁用失败");
      }
    },
  });
};

// 表单提交成功
const handleFormSuccess = () => {
  formVisible.value = false;
  fetchApplicationList();
};

// 初始化
onMounted(() => {
  fetchUserList();
  fetchApplicationList();
});
</script>

<style lang="scss" scoped>
.application-container {
  padding: 16px;

  .search-card {
    margin-bottom: 16px;

    :deep(.ant-card-body) {
      padding: 16px;
    }

    .search-form {
      .search-row {
        display: flex;
        gap: 16px;
        margin-bottom: 16px;

        .search-item {
          flex: 0 0 calc(33.333% - 11px);
          margin-bottom: 0;

          :deep(.ant-form-item-label) {
            width: 80px;
            text-align: right;
          }

          :deep(.ant-form-item-control) {
            flex: 1;
          }
        }
      }

      .search-buttons {
        :deep(.ant-form-item-label) {
          display: none;
        }

        :deep(.ant-space) {
          display: flex;
          justify-content: flex-start;
        }
      }
    }
  }
  .table-card {
    :deep(.ant-card-head) {
      min-height: 48px;
      padding: 0 16px;

      .ant-card-head-title {
        padding: 12px 0;
      }
    }
    :deep(.ant-card-body) {
      padding: 16px;
    }

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      width: 100%;
    }
  }

  .pagination-container {
    margin-top: 16px;
    text-align: right;
  }

  .action-btns {
    display: flex;
    gap: 4px;
    justify-content: center;
  }
}
</style>
